package com.lottery.im.api;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import java.util.concurrent.TimeUnit;

/**
 * Created by lianwufeng on 2017/8/10.
 *
 * 设置请求失败后的延迟重连时间以及次数
 */

public class RetryWithDelay implements
    Function<Observable<? extends Throwable>, Observable<?>> {

  private final int maxRetries;
  private final int retryDelayMillis;
  private int retryCount;

  public RetryWithDelay(int maxRetries, int retryDelayMillis) {
    this.maxRetries = maxRetries;
    this.retryDelayMillis = retryDelayMillis;
    this.retryCount = 0;
  }

  @Override public Observable<?> apply(@NonNull Observable<? extends Throwable> observable)
      throws Exception {
    return observable
        .flatMap((Function<Throwable, ObservableSource<?>>) throwable -> {
          if (++retryCount <= maxRetries) {
            return Observable.timer(retryDelayMillis,
                TimeUnit.MILLISECONDS);
          }
          return Observable.error(throwable);
        });
  }
}